#include "logger.h"

Category * Logger::_root = nullptr;
Logger * Logger::_pInstance = nullptr;

Logger::Logger(){
    //将log4cpp的相关初始化的代码全部放到构造函数中去编写
    //因为单例的构造函数只会被执行一次
    //log4cpp里面的appender、layout等其实也只需要执行一次
    
    PatternLayout * pl1 = new PatternLayout();
    pl1->setConversionPattern("%d %c [%p] %m%n");

    OstreamAppender * ap1 = new OstreamAppender("console", &cout);
    ap1->setLayout(pl1);
    
    PatternLayout * pl2 = new PatternLayout();
    pl2->setConversionPattern("%d %c [%p] %m%n");
    FileAppender * ap2 = new FileAppender("file", "wd.log");
    ap2->setLayout(pl2);


    Category & root = Category::getRoot();
    root.setPriority(Priority::ERROR);
    root.addAppender(ap1);
    root.addAppender(ap2);
    _root = &root;
}
Logger::~Logger(){
    //回收资源 这个步骤不做也没有关系
    Category::shutdown();
}

Logger * Logger::getInstance(){
    if(_pInstance == nullptr){
        _pInstance = new Logger();
    }
    return _pInstance;
}
void Logger::destroy(){
    if(_pInstance){
        delete _pInstance;
        _pInstance = nullptr;
    }
}
void Logger::warn(const char * file, int line, const char * func, const char * msg){
    string content = "文件:" + string(file) + "行号:" + to_string(line) + "函数名称:" + func + msg;
    _root->warn(content);
}
void Logger::error(const char * file, int line, const char * func, const char * msg){
    string content = "文件:" + string(file) + "行号:" + to_string(line) + "函数名称:" + func + msg;
    _root->error(content);
}
void Logger::debug(const char * file, int line, const char * func, const char * msg){
    string content = "文件:" + string(file) + "行号:" + to_string(line) + "函数名称:" + func + msg;
    _root->debug(content);
}
void Logger::info(const char * file, int line, const char * func, const char * msg){
    string content = "文件:" + string(file) + "行号:" + to_string(line) + "函数名称:" + func + msg;
    _root->info(content);
}
int main(){
  LOG_DEBUG("DEBUG 日志：不会输出");  // 优先级 < ERROR，过滤
    LOG_INFO("INFO 日志：不会输出");    // 优先级 < ERROR，过滤
    LOG_WARN("WARN 日志：不会输出");    // 优先级 < ERROR，过滤
    LOG_ERROR("ERROR 日志：会输出");    // 优先级 = ERROR，输出

    return 0;
}
